package com.pro01.backend.mapper;

import com.pro01.backend.dto.PromotionActiveDTO;
import com.pro01.backend.pojo.Promotion2;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface Promotion2Mapper {

    // 管理员设置促销
    @Insert("""
        INSERT INTO promotions2 (torrent_id, promotion_type, start_time, end_time)
        VALUES (#{torrentId}, #{promotionType}, #{startTime}, #{endTime})
    """)
    int insertPromotion(Promotion2 promotion);

    // 管理员取消促销
    @Delete("DELETE FROM promotions2 WHERE torrent_id = #{torrentId}")
    int deletePromotionByTorrentId(@Param("torrentId") Long torrentId);

    // 用户查看当前有效促销
    @Select("""
        SELECT
            t.id AS torrent_id,
            t.name,
            t.category,
            t.size,
            p.promotion_type,
            p.end_time
        FROM promotions2 p
        JOIN torrents t ON p.torrent_id = t.id
        WHERE p.end_time > NOW()
        ORDER BY p.end_time ASC
        LIMIT #{limit} OFFSET #{offset}
    """)
    List<PromotionActiveDTO> getActivePromotions(@Param("offset") int offset,
                                                 @Param("limit") int limit);

    @Select("SELECT COUNT(*) FROM promotions2 WHERE end_time > NOW()")
    int countActivePromotions();

    // 查询可用的促销
    @Select("SELECT * FROM promotions2 WHERE torrent_id = #{torrentId} AND end_time > NOW() LIMIT 1")
    Promotion2 getActivePromotionByTorrentId(@Param("torrentId") Long torrentId);

}

